package com.department.mydepartment.service;

import com.department.mydepartment.fastdfs.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class UploadService {
    @Value("${fastdfs.base.url}")
    private String FASTDFS_BASE_URL;
    @Autowired
    private StorageService storageService;

    public Map<String, Object> upload(@RequestPart("file")MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        if (file != null) {
            try {
                String msg = writeFile(file);
                if (msg != null){
                    result.put("fileName",msg);
                }else {
                    result.put("fileName","");
                }
            }catch (Exception e){
                System.out.println(e.getMessage());
                result.put("fileName","");
            }
        }
        return result;
    }
    public Map<String,Object> delete(@RequestParam("fileId") String fileId){
        Map<String,Object> result = new HashMap<>();

        if(!"".equals(fileId)){
            result.put("code",storageService.delete(fileId));
        }
        return result;
    }

    private String writeFile(MultipartFile multipartFile) throws IOException {
        String oName = multipartFile.getOriginalFilename();
        String extName = oName.substring(oName.lastIndexOf(".") + 1);
        String uploadUrl = null;
        try {
           uploadUrl = FASTDFS_BASE_URL + storageService.upload(multipartFile.getBytes(), extName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //uploadUrl = fastDFSStorageService.upload(multipartFile.getBytes(), extName);
        return uploadUrl;
    }
}
